package cc.facesign.acl.service.impl;

import cc.facesign.acl.bean.AclRole;
import cc.facesign.acl.bean.AclRoleMenu;
import cc.facesign.acl.mapper.AclRoleMapper;
import cc.facesign.acl.service.AclRoleMenuService;
import cc.facesign.acl.service.AclRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限角色 服务实现类
 * </p>
 *
 * @author acdongla
 * @since 2022-05-02
 */
@Service
@Transactional
public class AclRoleServiceImpl extends ServiceImpl<AclRoleMapper, AclRole> implements AclRoleService {


    @Autowired
    private AclRoleMenuService roleMenuService;

    @Override
    public List<AclRole> getListByUserId(String userId) {
        return baseMapper.getRoleListByUserId(userId);
    }

    @Override
    public void addMenuList(String roleId, List<String> menuIds) {

        roleMenuService.deleteByRoleId(roleId);

        List<AclRoleMenu> list = new ArrayList<>();
        for (String menuId : menuIds) {
            if (!roleMenuService.existRelate(roleId, menuId))
                list.add(new AclRoleMenu(roleId, menuId));
        }

        roleMenuService.relateBatch(list);
    }

    @Override
    public void delete(String roleId) {
        // 删除关联信息
        roleMenuService.deleteByRoleId(roleId);
        // 删除角色
        removeById(roleId);
    }

    @Override
    public boolean isRelate(String userId, String rokeKey) {
        List<String> list = getListByUserId(userId).stream()
                .map(x -> x.getRokeKey())
                .collect(Collectors.toList());

        return list.contains(rokeKey);
    }

}
